<template>
  <el-container class="bigbox">
    <el-header>
            <img src="../../image/study.jpg">
            <span>微服务卷B</span>
    </el-header>
    <el-container>
    <!--左侧-->
    <el-aside  style="position: relative;" ></el-aside>

    <!--右侧-->
    <el-main>
      <div class="fromBox">
        <div class="signup_div">
            <span class="signup-btn" :class="{'bottom' : bottom.active}" id="signup_btn" @click="signupBtn">登录</span>
            <span class="line">|</span>
            <span class="signdown-btn" :class="{'bottom' : !bottom.active}" id="signdown_btn"   @click="signdownBtn">注册</span>
        </div>
        <el-form v-if="signupOrSigndown" ref="loginRefForm" :model="user" label-width="100px"  :rules="loginRules">
                  <el-form-item label="账号" prop="username">
                    <el-input v-model="user.username" placeholder="4到16位(字母,数字,下划线,减号)" />
                  </el-form-item>
                  <el-form-item label="密码" prop="password">
                    <el-input type="password" v-model="user.password" placeholder="6到18位数字" />
                  </el-form-item>
                  <el-form-item>
                    <el-button class="signupBtn" type="primary" @click="login">登 录</el-button>
                  </el-form-item>
        </el-form>
        <el-form v-else  ref="loginRefForm" :model="userSignIn" class="signUp" label-width="100px" :rules="signInRules" >
                  <el-form-item label="用名：" prop="username">
                      <el-input v-model="userSignIn.username"   placeholder="4到16位(字母,数字,下划线,减号)"/>
                  </el-form-item>
                  <el-form-item label="密码：" prop="password">
                      <el-input v-model="userSignIn.password" type="password" placeholder="6到18位数字" />
                  </el-form-item>
                  <el-form-item label="确认密码：" prop="passwordAgain">
                      <el-input v-model="userSignIn.passwordAgain" type="password"  placeholder="请再次输入密码"/>
                  </el-form-item>
                  <el-form-item>
                      <el-button type="primary" class="signDownBtn" @click="signIn">注册</el-button>
                  </el-form-item>
        </el-form>
      </div>
    </el-main>
    </el-container>
  </el-container>
</template>

<script setup>
import {getCurrentInstance  ,ref, onMounted, reactive} from 'vue'
import {doGet, doPost} from "../../http/httpUserRequest.js";
import {getTokenName, messageTip, removeToken} from "../../util/util.js";

  //定义页面使用到的变量，定义时初始值都是给个空的
  let signupOrSigndown = ref(true);
  let bottom = reactive({ active:true  });
  //对象变量定义，是{}
  let user = reactive({});
  let userSignIn = reactive({
    username:'',
    password:'',
    passwordAgain:""
  });
  //字符串变量定义，是''
  let name = ref('');
  //定义登录表单的验证规则
  let loginRules = {
    //定义账号的验证规则，规则可以有多个，所以是数组
    username : [
      { required: true, message: '请输入登录账号', trigger: 'blur' }
    ],
    //定义密码的验证规则，规则可以有多个，所以是数组
    password : [
      { required: true, message: '请输入登录密码', trigger: 'blur' },
      { min: 6, max: 16, message: '登录密码长度为6-16位', trigger: 'blur' }
    ],
  };
  //定义注册表单的验证规则
  let signInRules = {
    //定义账号的验证规则，规则可以有多个，所以是数组
    username : [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 4, max: 16, message: '用户名长度应在4到16个字符之间', trigger: 'blur' }
    ],
    //定义密码的验证规则，规则可以有多个，所以是数组
    password : [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 6, max: 18, message: '密码长度应在6到18个字符之间', trigger: 'blur' }
    ],
        //定义密码的验证规则，规则可以有多个，所以是数组
    passwordAgain : [
      { required: true, message: '请确认密码', trigger: 'blur' },
      { validator: checkPasswordAgain, trigger: 'blur' }
    ],

  };
  //getCurrentInstance() 是一个用于访问当前组件实例的工具
  const instance = getCurrentInstance();

  //页面渲染dom元素后会触发调用该函数（函数钩子）
  onMounted(()=>{
    freeLogin();
  });
  //注册密码验证两次输入是否一样
  function checkPasswordAgain(rule, value, callback) {
    if (value != userSignIn.password) {
      callback(new Error('两次输入的密码不一致'));
    } else {
      callback();
    }
  };
  //切换注册登录按钮
  function signupBtn() {
        bottom.active=true
        signupOrSigndown = true
  };
  function signdownBtn() {
        bottom.active=false
        signupOrSigndown = false
  };

  //注册函数
  function signIn(){
    //提交前验证输入框的合法性
    if(!instance){
      return
    }
    instance.refs.loginRefForm.validate( (isValid) => {
      //isValid是验证后的结果，如果是true表示验证通过，否则未通过
      if (isValid) {
        //验证通过，可以提交注册
        let formData = new FormData();
        formData.append("username", userSignIn.username);
        formData.append("password", userSignIn.password);
        doPost("/user/signIn", formData).then( (resp) => {
          if (resp.data.code === 200) {
            //登录成功，提示一下
            messageTip("登录成功", "success");
            //删除一下历史localStorage和sessionStorage中存储的token
            removeToken();
            //跳转到登录页面
            window.location.href = "/";
          } else {
            //登录失败，也提示一下
            messageTip("登录失败", "error");
          }
        });
      }
    })
  };
    //登录函数
  function login() {
      //提交前验证输入框的合法性
      if(!instance){
          return 
      }
      instance.refs.loginRefForm.validate( (isValid) => {
        //isValid是验证后的结果，如果是true表示验证通过，否则未通过
        if (isValid) {
          //验证通过，可以提交登录
          let formData = new FormData();
          formData.append("loginAct", user.loginAct);
          formData.append("loginPwd", user.loginPwd);
          formData.append("captcha",user.captcha)
          formData.append("rememberMe", user.rememberMe);
          doPost("/user/login", formData).then( (resp) => {
            if (resp.data.code === 200) {
              //登录成功，提示一下
              messageTip("登录成功", "success");

              //删除一下历史localStorage和sessionStorage中存储的token
              removeToken();

              //前端存储jwt
              if (user.rememberMe === true) {
                window.localStorage.setItem(getTokenName(), resp.data.data);
              } else {
                window.sessionStorage.setItem(getTokenName(), resp.data.data);
              }
              //跳转到系统的主页面
              window.location.href = "/dashboard";
            } else {
              //登录失败，也提示一下
              messageTip("登录失败", "error");
            }
          });
        }
      })
    };
  // //更新验证码
  // function refreshCaptcha(){
  //     captchaUrl = captchaUrl;
  // }
    //免登录（自动登录）
  function freeLogin() {
      let token = window.localStorage.getItem(getTokenName());
      if (token) { //表示token有值，token不是空，token存在
        doGet("/user/login/free", {}).then(resp => {
          if (resp.data.code === 200)  {
            //token验证通过了，那么可以免登录
            window.location.href = "/dashboard";
          }
        })
      }
    };
</script>

<style scoped>
.captchaImg{
  margin-left: 20px;
}
.signupBtn{
  width: 100px;
  margin-right: 20px;
}
.bigbox{
  height: calc(98vh);
  width: 100%;
}
.fromBox{
  border: 1px solid grey;
  box-shadow:  0px 0px 10px 1px grey;
  border-radius: 4px;
  width: 441px;
  height: 303px;
  margin: auto;
  margin-top: 20%;
}
.signup_div{
    margin-bottom: 30px;
    margin-top: 30px;
    margin-left: 50px;
}
.signup_div  .line{
    font-size: 20px;
}
.signup_div  .signdown-btn{
    font-size: 25px;
    font-weight: bold;
    cursor: pointer;

}
.signup_div  .signdown-btn:hover{
    color: #393939;
}
.bottom{
    border-bottom: 6px solid skyblue;
}
.signup_div  .signup-btn{
    font-size: 25px;
    font-weight: bold;
}
.signup_div  .signup-btn:hover{
    color: #393939;
    cursor: pointer;

}
.left-image{
  width: 100%;
}
.el-input{
  width: 80%;
}

.el-aside {
  background: #1a1a1a;
  width: 50%;
  background:url(../../image/SignUp.jpg);
  background-repeat: no-repeat;
  background-size: cover;
}
.el-main {
  height: 100%;
}

.imgTitle {
  color: #f9f9f9;
  font-size: 28px;
}
.loginTile {
  text-align: center;
  margin-top: 100px;
  margin-bottom: 25px;
  font-weight: bold;
}

.el-header{
    width: 100%;
    height: 8%;
    background-color: #393939;
    position: relative;
}
.el-header span{
    font-weight: bold;
    font-size: 30px;
    font-style: italic;
    vertical-align: top;
    line-height: 250%;
}
.el-header img{
    width: 4%;
    height: 100%;
    margin-left: 2%;
}

</style>